local http = require "resty.http"
local cjson = require "cjson"
local mysql = require "lualib.mysql"

local httpc 

local address = {
    ["127.0.0.1"] = true,
}

local function tmp_del_user(username)
    local fmt = [===[
    delete from chat.users where `username` = '%s'
    ]===]
    local sql = string.format(fmt, username)
    mysql.process_mysql_query(sql)
end 

local function signup(addr, uuid, token)
    if not address[addr] then 
        return cjson.encode({ code = 500, status = false, msg = "Address not allowed for registration" })
    end 

    -- token: user\tpass
    local username, password = token:match("(%w+)\t(%w+)")
    
    tmp_del_user(username) -- 临时删除一下之前有的用户

    -- 查询用户是否存在
    local fmt = [===[
    select * from chat.users where `username` = '%s' limit 1 
    ]===]

    local sql = string.format(fmt, username)
    local row = mysql.process_mysql_query(sql)
    
    -- exist user 
    if row and row[1] then 
        ngx.log(ngx.ERR, "exist user: ", username)
        return cjson.encode({ code = 500, status = false, msg = "exist user" })
    end 

    -- 执行用户注册

    local fmt = [===[
    insert into chat.users(`uid`, `username`, `password`, `exp`, `updated`) values (%d, '%s', '%s', %d, '%s')
    ]===]

    local time = os.date("%Y-%m-%d %H:%M:%S")

    local sql = string.format(fmt, uuid, username, password, 0, time)
    mysql.process_mysql_query(sql)

    return cjson.encode({ code = 200, status = true, msg = "signup success!" })
end 


local function main() 
    ngx.req.read_body()
    local postfields = ngx.req.get_post_args()
    local addr_port = tostring(postfields.addr_port)
    -- 127.0.0.1:54839
    local addr, port = addr_port:match("([^:]+):(%w+)")
    local token = postfields.token
    local uuid = postfields.uuid
    
    local ok, JS_result = pcall(signup, addr, uuid, token)

    if ok then 
        ngx.status = ngx.HTTP_OK
        ngx.say(JS_result)
        return ngx.exit(ngx.HTTP_OK)
    end 
    
    ngx.status = 500
    ngx.say("Internal Server Error")
    return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end

main()